import axios from 'axios';

axios.defaults.baseURL = config.baseUrl;
axios.defaults.timeout = 30000;
axios.defaults.withCredentials = true; //意思是携带cookie信息,保持session的一致性
axios.defaults.headers.post['Content-Type'] = 'application/json';

var closeWait = function(obj) {
	//如果存在params或data,获取_wait字段
	var _wait;
	if(obj.config && obj.config.params) {
		_wait = obj.config.params._wait;
	}
	if(obj.config && obj.config.data) {
		var data = obj.config.data;
		if(typeof data == "string") {
			data = JSON.parse(data);
		}
		_wait = data._wait;
	}
	if(_wait != null) {
		loading.close();
	}
}
var loading;
var openWait = function(config) {
	//如果参数中的_wait字段是true,则打开等待框,并把等待框的id存回_wait
	if(config.params && config.params._wait != null) {
		loading = tool.loading({
			text: config.params._wait,
			background: "rgba(0,0,0,0.5)"
		});
	}
	if(config.data && config.data._wait != null) {
		loading = tool.loading({
			text: config.data._wait,
			background: "rgba(0,0,0,0.5)"
		});
	}
}

//request 拦截器
axios.interceptors.request.use(
	config => {

		openWait(config);
		//携带头部token

		if(config.headers['token'] == "talkcloud") {
			config.baseURL = "http://global.talk-cloud.net/";
			config.withCredentials = false;
		} else {
			config.headers['token'] = tool.getItem(lsKey.token);
		}

		return config;
	},
	error => {
		var message = "系统错误：" + error.message;

		tool.message({
			showClose: true,
			message: message,
			type: 'error'
		});
		return Promise.reject(message);
	}
);

//response 拦截器
axios.interceptors.response.use(

	response => {
		//关闭等待框

		closeWait(response);
		var result = response.data;
		
		//闯关系统上传文件接口相关
		if(result.type) {
			return response;
		}
		
		//请求域名与默认不一致,第三方的接口,直接返回
		if(response.config.baseURL != config.baseUrl) {
			return result;
		}
		//解析正常的接口,无异常,返回数据
		if(result.status == "success") {
			return result.data;
		}
		//有异常
		var msg;
		var errorMsg = function(m) {
			msg = m;
			tool.message({message: msg, type: 'error'});
		};

		//处理系统异常
		switch(result.errorCode) {
			case 9999:
				errorMsg("系统异常：9999");
				break;
			case 401:
				//跳转到登录页
				tool.removeItem(lsKey.token);
				store.commit("clearAll");
				router.push("/login");
				break;
			case 1001:
				errorMsg("该记录已存在：1001");
				break;
			case 1002:
				errorMsg("用户权限不足：1002");
				break;
			case 1004:
				errorMsg("参数解析异常：1004");
				break;
			case 1008:
				errorMsg("当前校区异常：1008");
				break;
			default:
				errorMsg(result.data.result);
		}
		return Promise.reject(msg);


	},
	error => {
		//关闭等待框
		closeWait(error);
		var message = "系统错误：" + error.message;

		tool.message({
			showClose: true,
			message: message,
			type: 'error'
		});
		return Promise.reject(message);
	}
)

window.axios = axios;